import {_get, _post} from '../network'
// 格式化文件大小
export function formatSize(size) {
    if (size === null) {
        return "-";
    } else if ((size / 1024) < 1024) {
        return (size / 1024).toFixed(2) + ' KB';
    } else if ((size / 1048576) < 1024) {
        return (size / 1048576).toFixed(2) + ' M';
    } else if ((size / 1073741824) < 1024) {
        return (size / 1073741824).toFixed(2) + ' G';
    } else {
        return 'error';
    }
}

// 上传文件 上传状态 0准备上传 1上传成功 2正在上传 3重试
export function uploadFile(files, path) {
    let _this = this;
    if (path === undefined) {
        path = "/"
    }
    let append = 0;
    for (const item of files) {
        append += item.file.size;
    }
    _get({
        url: 'system/disk/enable-upload',
        params: {
            append
        }
    }).then(rsp => {
        if (rsp.data.code === "00000") {
            _this.clicked = true;
            for (let i = 0; i < files.length; i++) {
                let item = files[i];
                // 获取上传链接
                _post({
                    url: 'system/disk/get-file-upload-url',
                    data: {
                        name: item.file.name,
                        size: item.file.size,
                        type: item.file.type,
                        path: path
                    }
                }).then((rsp) => {
                    // 成功获取上传链接
                    if (rsp.data.code === '00000') {
                        const image = new RegExp("image");
                        if (image.test(item.file.type)) {
                            saveThumbnailBase64(item.file, rsp.data.object.key);
                        }
                        let url = rsp.data.object.url;
                        let xhr = new XMLHttpRequest();
                        xhr.open('PUT', url, true);
                        // 上传成功
                        xhr.onload = () => {
                            item.status = 1
                        };
                        // 开始上传
                        xhr.onloadstart = () => {
                            item.status = 2
                        }
                        // 上传失败
                        xhr.onerror = () => {
                            item.status = 3
                        };
                        // 上传回调
                        xhr.upload.onprogress = (event) => {
                            let total = event.total;
                            let loaded = event.loaded;
                            item.progress = ((loaded / total) * 100).toFixed(1);
                        }
                        // 发送请求
                        xhr.send(item.file);
                        // 获取上传链接失败
                    } else {
                        item.status = 3
                    }
                }).catch((error) => {
                    console.log(error)
                    item.status = 3
                })
            }
        } else {
            _this.$error({message: rsp.data.msg})
        }
    }).catch(error => {
        console.log(error);
        _this.$serverError();
    })
}

// 重新上传
export function reUpload(item) {
    let _this = this;
    let path = _this.$route.query.path;
    if (path === undefined) {
        path = "/"
    }
    _post({
        url: 'system/disk/get-file-upload-url',
        data: {
            name: item.file.name,
            size: item.file.size,
            type: item.file.type,
            path: path
        }
    }).then((rsp) => {
        // 成功获取上传链接
        if (rsp.data.code === '00000') {
            let url = rsp.data.object;
            let xhr = new XMLHttpRequest();
            xhr.open('PUT', url, true);
            // 上传成功
            xhr.onload = () => {
                item.status = 1
            };
            // 开始上传
            xhr.onloadstart = () => {
                item.status = 2
            }
            // 上传失败
            xhr.onerror = () => {
                _this.$error({message: '文件上传失败'})
                item.status = 3
            };
            // 上传回调
            xhr.upload.onprogress = (event) => {
                let total = event.total;
                let loaded = event.loaded;
                item.progress = ((loaded / total) * 100).toFixed(1);
            }
            // 发送请求
            xhr.send(item.file);
            // 获取上传链接失败
        } else {
            _this.$error({message: rsp.data.msg})
            item.status = 3
        }
    }).catch((error) => {
        console.log(error)
        _this.$error({message: '服务器繁忙'})
        item.status = 3
    })
}

// 获取图片file文件的base64
export function saveThumbnailBase64(file, key) {
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
        // 获取图片文件的base64编码
        let originalBase64 = e.target.result.toString();
        // 压缩base64
        let img = document.createElement('img')
        img.onload = () => {
            let width = img.width;
            let height = img.height;
            let thumbnailHeight = height * (300 / width);
            let canvas = document.createElement("canvas");
            canvas.width = 300;
            canvas.height = thumbnailHeight;
            let ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, 300, thumbnailHeight);
            let thumbnailBase64 = canvas.toDataURL('image/jpeg', 0.1)
            _post({
                url: 'system/disk/save-thumbnail',
                data: {
                    base64Url: thumbnailBase64,
                    key: key
                }
            }).then(rsp => {
                console.log("保存缩略图成功")
            }).catch(error => {
                console.log("保存缩略图失败")
            })
        }
        img.src = originalBase64;
    }
    fileReader.readAsDataURL(file)
}

// 根据type判断icon
export function getIconByType(type, name) {
    if (/folder/.test(type)) {
        // 未文件夹
        return {icon: 'mdi-folder', color: '#ffd659'};
    } else {
        // 不是文件夹
        let suffix = name.substring((name.lastIndexOf(".") + 1))
        switch (suffix) {
            // 音频文件
            case "mp3" :
            case "flac" :
                return {icon: 'mdi-file-music', color: '#8183f1'}
            // 图片文件
            case "jpg":
            case "png":
            case "webp":
            case "jpeg":
                return {icon: 'mdi-file-image', color: '#ff7743'}
            // 文本文件
            case "txt":
                return {icon: 'mdi-file-document', color: '#BCAAA4'}
            // 视频文件
            case "mp4":
            case "mov":
                return {icon: 'mdi-file-video', color: '#43A047'}
            // word
            case "docx":
            case "doc":
                return {icon: 'mdi-file-word', color: '#4d97ff'}
            // pdf
            case "pdf":
                return {icon: 'mdi-file-pdf', color: '#ff5a5a'}
            // ppt
            case "ppt":
            case "pptx":
                return {icon: 'mdi-file-powerpoint', color: '#ff9743'}
            // excel
            case "xls":
            case "xlsx":
                return {icon: 'mdi-file-excel', color: '#00838F'}
            // apk
            case "apk":
                return {icon: 'mdi-android-debug-bridge', color: '#63c422'}
            // 压缩文件
            case "zip":
            case "rar":
            case "gz":
            case "z":
            case "arj":
                return {icon: 'mdi-zip-box', color: '#E53935'}
            // 没有匹配到文件
            default:
                return {icon: 'mdi-file-cloud', color: '#b9c9d6'};
        }
    }
}

// 过滤文件列表
export function filterList(value, originalList) {
    let filteredList = [];
    if (value === '') {
        filteredList = originalList;
    } else {
        for (const item of originalList) {
            if (item.name.toString().toLocaleLowerCase().indexOf(value.toString().toLocaleLowerCase()) !== -1) {
                filteredList.push(item)
            }
        }
    }
    return filteredList;
}

// 获取头像链接，需要有一个avatarSrc
export function getAvatarLink() {
    let _this = this;
    _this._get({
        url: 'user/get-avatar-link'
    }).then(rsp => {
        _this.avatarSrc = rsp.data;
    }).catch(error => {
        console.log(error);
    });
}

export function getCode() {
    let _this = this;
    if (_this.$refs['email'].validate()) {
        _this.codeBtn.loading = true;
        _this._get({
            url: 'open/get-verification-code',
            params: {
                email: _this.email
            }
        }).then((rsp) => {
            let code = rsp.data.code;
            if (code === '00000') {
                _this.$success({message: '验证码发送成功'});
                // 调用按钮倒计时
                _this.countDown();
            } else {
                _this.$error({message: rsp.data.msg});
            }
        }).catch((error) => {
            console.log(error)
            _this.$error({message: '服务器繁忙'});
        }).finally(() => {
            _this.codeBtn.loading = false
        })
    }
}

export function getCapacity() {
    let _this = this;
    _this._get({
        url: 'system/disk/get-capacity'
    }).then(rsp => {
        _this.$store.commit("setCapacityData", rsp.data);
    }).catch(error => {
        console.log(error);
        _this.$serverError();
    })
}

export function logout(showPrompt) {
    let _this = this;
    _this._post({
        url: 'login-out'
    }).then(rsp => {
        if (rsp.data.code === '00000') {
            sessionStorage.clear();
            _this.$router.push("/home");
            if (showPrompt === true) {
                _this.$success({message: '退出成功'})
            }
        }
    }).catch(error => {
        console.log(error);
        _this.$serverError();
    })
}
